<script setup lang="ts">
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { reactive } from 'vue'
import { ref } from 'vue'
import { getDataApi, saveFormApi } from '@/api/system'
import { onMounted } from 'vue'

const props = defineProps({
  isShow: {
    type: Boolean,
    default: false
  },
  title: {
    type: String,
    default: ''
  },
  fromInfo: {
    type: Object,
    default: () => {}
  }
})

const emit = defineEmits<{
  (e: 'update:isShow', value: boolean): void
  (e: 'getNewInfoFn'): void
  (e: 'getTableData'): void
}>()

const ruleFormRef = ref<any>()
const form = ref({
  sqlId: 'noticeMgr.addNotice',
  role_id: [],
  notice_id: '',
  notice_name: '',
  end_date: '',
  push_flag: false, // 0:不推送 1:推送首页
  notice_content: ''
})

const resetFrom = ref({
  sqlId: 'noticeMgr.addNotice',
  role_id: [],
  notice_id: '',
  notice_name: '',
  end_date: '',
  push_flag: false, // 0:不推送 1:推送首页
  notice_content: ''
})

if (props.title === '修改公告') {
  form.value.role_id = props.fromInfo.role_id.split(',')
  form.value.notice_name = props.fromInfo.notice_name
  form.value.end_date = props.fromInfo.end_date
  form.value.notice_content = props.fromInfo.notice_content
  form.value.notice_id = props.fromInfo.notice_id
} else {
  form.value = resetFrom.value
}
interface RuleForm {
  notice_name: string
  end_date: string
  role_id: string
  notice_content: string
}

const rules = reactive<FormRules<RuleForm>>({
  notice_name: [{ required: true, message: '请输入公告名称', trigger: 'blur' }],
  end_date: [{ required: true, message: '请输入过期时间', trigger: 'blur' }],
  role_id: [{ required: true, message: '请选择角色', trigger: 'blur' }],
  notice_content: [{ required: true, message: '请输入公告内容', trigger: 'blur' }]
})

const JueSeOptions = ref<any>([])
const getJueSeData = async () => {
  const params = {
    sqlId: 'roleMgr.getRoleInfo'
  }
  await getDataApi(params)
    .then((res) => {
      JueSeOptions.value = res
    })
    .catch(() => {
      ElMessage({ message: '角色获取失败', type: 'error' })
    })
}

const saveFormFn = async () => {
  const params = {
    sqlId: form.value.sqlId,
    notice_name: form.value.notice_name,
    end_date: form.value.end_date,
    notice_id: form.value.notice_id,
    role_id: form.value.role_id.join(','),
    push_flag: form.value.push_flag ? '1' : '',
    notice_content: form.value.notice_content
  }
  await saveFormApi(params)
    .then((res: any) => {
      if (res === 'success') {
        form.value = resetFrom.value
        ElMessage({ message: '添加成功', type: 'success' })
      } else {
        ElMessage({ message: '添加失败', type: 'error' })
      }
    })
    .catch(() => {
      ElMessage({ message: '添加失败', type: 'error' })
    })
    .finally(() => {
      emit('getTableData')
    })
}

const Cancel = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  form.value = resetFrom.value
  emit('update:isShow', false)
}

const Confirm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid) => {
    if (valid) {
      // console.log('submit!', form.value)
      saveFormFn()
    } else {
      ElMessage({ message: '请输入完整信息', type: 'error' })
    }
  })
  emit('getNewInfoFn')
  emit('update:isShow', false)
}

onMounted(() => {
  getJueSeData()
})
</script>
<template>
  <el-dialog :model-value="isShow" :title="title" width="70%" @close="Cancel(ruleFormRef)">
    <el-form :model="form" ref="ruleFormRef" :rules="rules" label-width="auto">
      <el-form-item label="公告名称" prop="notice_name">
        <el-input v-model="form.notice_name" />
      </el-form-item>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="过期时间" prop="end_date">
            <el-date-picker
              v-model="form.end_date"
              type="datetime"
              placeholder="选择过期时间"
              value-format="YYYY-MM-DD HH:mm:ss"
              style="width: 240px"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="接收角色(选填)" prop="role_id">
            <el-select
              v-model="form.role_id"
              multiple
              collapse-tags
              placeholder="请选择授权类型"
              style="width: 240px"
            >
              <el-option
                v-for="item in JueSeOptions"
                :key="item.role_id"
                :label="item.role_name"
                :value="item.role_id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="首页推送">
            <el-checkbox v-model="form.push_flag"></el-checkbox>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="公告内容" prop="notice_content">
        <el-input v-model="form.notice_content" :rows="10" type="textarea" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="Cancel(ruleFormRef)">取消</el-button>
        <el-button type="primary" @click="Confirm(ruleFormRef)"> 确定 </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<style scoped lang="less"></style>
